package payjs.api;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.convert.Convert;
import jodd.http.HttpRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import payjs.entity.ClientPayInfo;
import payjs.entity.PayInfo;
import payjs.entity.PayJSConfig;
import payjs.entity.response.Order;
import payjs.entity.response.ScanResult;
import payjs.util.SignUtil;

@Data
@AllArgsConstructor
public class WxPayApi {
	private PayJSConfig payConfig;

	private final String url_base = "https://payjs.cn/api";
	/** 扫码 */
	private final String url_scan = "/native";
	/** 客户端 */
	private final String url_client = "/cashier";
	/** 订单查询 */
	private final String url_order = "/check";
	

	public ScanResult scan(PayInfo payInfo) {
		Map<String, String> map = new HashMap<>();
		map.put("mchid", payConfig.getMchid());
		map.put("total_fee", Convert.toStr(payInfo.getTotal_fee()));
		map.put("out_trade_no", payInfo.getOut_trade_no());
		map.put("body", payInfo.getBody());
		map.put("attach", payInfo.getAttach());
		map.put("notify_url", payInfo.getNotify_url());// 回调地址
		map.put("sign", SignUtil.sign(map, payConfig.getKey()).toUpperCase());

		map.put("body", payInfo.getBody());
		map.put("notify_url", map.get("notify_url"));
		String json = HttpRequest.post(url_base + url_scan).query(map).send().bodyText();
		return JSONObject.parseObject(json, ScanResult.class);
	}

	/** 收银台 */
	public ClientPayInfo client(ClientPayInfo payInfo) {
		Map<String, String> map = new HashMap<>();
		map.put("mchid", payConfig.getMchid());
		map.put("total_fee", Convert.toStr(payInfo.getTotal_fee()));
		map.put("out_trade_no", payInfo.getOut_trade_no());
		map.put("body", payInfo.getBody());
		map.put("attach", payInfo.getAttach());
		map.put("notify_url", payInfo.getNotify_url());// 回调地址
		map.put("callback_url", payInfo.getCallback_url());// 用户支付成功后，前端跳转地址
		
		payInfo.setSign(SignUtil.sign(map, payConfig.getKey()).toUpperCase());
		payInfo.setUrl_form(url_base + url_client);
		return payInfo; // 给前端表单
	}
	
	public Order getOrder(String orderId){
		Map<String, String> map = new HashMap<>();
		map.put("payjs_order_id", orderId);
		map.put("sign", SignUtil.sign(map, payConfig.getKey()).toUpperCase());
		String json = HttpRequest.post(url_base + url_order).query(map).send().bodyText();
		return JSONObject.parseObject(json, Order.class);
	}

}
